package com.peanut.huibutie.openapi;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.peanut.huibutie.common.AppConfig;
import com.peanut.huibutie.common.HttpInvoker;
import com.peanut.huibutie.common.OpenApiResult;
import com.peanut.huibutie.common.UserContext;
import com.peanut.huibutie.entity.UserVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class GetAccessTokenByAuthCode {
    @Resource
    private HttpInvoker httpInvoker;
    @Resource
    private UserContext userContext;

    public void invoke(String authCode) {
        Map<String, String> map = new HashMap<>();
        map.put("auth_code", authCode);
        OpenApiResult<JSONObject> openApiResult = httpInvoker.sendGet(AppConfig.GetAccessTokenByAuthCode_URL, map, JSONObject.class);
        if (openApiResult.isSuccess()) {
            JSONObject data = openApiResult.getData();
            String accessToken = data.getString("access_token");
            String openId = data.getString("open_id");
            String expireTime = data.getString("expire_time");
            UserVO userVO = new UserVO();
            userVO.setAccessToken(accessToken).setOpenId(openId)
                    .setExpireTime(DateUtil.parse(expireTime, "yyyy-MM-dd HH:mm:ss").toJdkDate());

            // 放入当前会话中
            userContext.setContext(userVO);
        }
    }
}
